package itsm.isperp.framework.security.access.vote;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

/**
 * 默认的vote处理<br/>
 * 
 * @author
 * 
 */
public class DefaultAuthenticatedVoter extends AuthenticatedVoter {
	private Log logger = LogFactory.getLog(DefaultAuthenticatedVoter.class);

	@Override
	public int vote(Authentication authentication, Object object,
			Collection<ConfigAttribute> attributes) {
		int vote = super.vote(authentication, object, attributes);
		if (vote != ACCESS_DENIED) {
			return getRightAttributes(authentication, attributes);
		}
		return vote;
		// return getRightAttributes(authentication, attributes);
	}

	/**
	 * 匹配正确的权限（注意不是所有权限，是当前地址匹配到的用户权限）
	 * 
	 * @param authentication
	 * @param attributes
	 * @return 如果没有匹配的返回null
	 */
	private int getRightAttributes(Authentication authentication,
			Collection<ConfigAttribute> attributes) {
		if ("admin".equals(authentication.getName())) {
			return ACCESS_GRANTED;
		}

		Collection<? extends GrantedAuthority> authorities = authentication
				.getAuthorities();

		for (ConfigAttribute attribute : attributes) {

			for (GrantedAuthority authority : authorities) {
				if (attribute.getAttribute().equals(authority.getAuthority())) {
					return ACCESS_GRANTED;
				}
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getRightAttributes() rightAttributes:" + attributes);
		}

		return ACCESS_DENIED;
	}

}
